from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS
from django.conf import settings


def generate_verify_email_url(user_id):
    # 生成验证邮箱链接
    # 加密一个用户的id, 并返回验证链接
    # http://www.meiduo.site:8000/emails/verification/?token=eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2OTU5MDAyNSwiZXhwIjoxNTY5NTkwMzI1fQ.eyJkYXRhIjoiYnVqaWEifQ.ggn0tKRJKnIZKjQ1WUoASRsJTXyQMhtLyvNsIivrQ6716zytp3sdyYtKDY3nIWXzF9Qt48I233Hl2gfTxfw4-A

    # 生成加密器
    s = TJWSS(secret_key=settings.SECRET_KEY, expires_in=300)

    token = s.dumps({'userid': user_id}).decode()
    # 加密器加密结果是 bytes 类型, 使用前需要 decode
    # eyJhbGciOiJIUzUxMiIsImlhdCI6MTU2OTU5MDAyNSwiZXhwIjoxNTY5NTkwMzI1fQ.eyJkYXRhIjoiYnVqaWEifQ.ggn0tKRJKnIZKjQ1WUoASRsJTXyQMhtLyvNsIivrQ6716zytp3sdyYtKDY3nIWXzF9Qt48I233Hl2gfTxfw4-A

    callback_url = 'http://www.meiduo.site:8000/emails/verification/?token='

    verify_email_url = callback_url + token

    return verify_email_url


def decode_email_token(token):
    # 解密token
    # 获取user id,
    # 返回user id

    # 生成加密器
    s = TJWSS(secret_key=settings.SECRET_KEY, expires_in=300)

    try:
        # 解密token
        data = s.loads(token)
    except Exception as e:
        print(e)
        # 解密失败就返回None
        return None

    # 获取userid
    user_id = data.get('userid')

    # 返回userid
    return user_id

